package com.ch01;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class MyExecutors {
    public boolean isRun = true;
    private BlockingDeque<Runnable> runnableDeque;

    public MyExecutors (int maxThreadCount, int dequeSize){
        // 限制队列的容量缓存
        runnableDeque = new LinkedBlockingDeque<>(dequeSize);
        // 创建好固定的线程
        for (int i=0; i<maxThreadCount; i++) {
            new WorkThread().start();
        }
    }

    class WorkThread extends Thread{
        @Override
        public void run() {
            while(isRun || runnableDeque.size()>0) {
                Runnable runnable = runnableDeque.poll();
                if (runnable != null) {
                    runnable.run();
                }
            }
        }
    }

    public boolean execute(Runnable runnable) {
        return runnableDeque.offer(runnable);
    }

    public static void main(String[] args) {
        MyExecutors myExecutors = new MyExecutors(2, 2);
        for (int i=0; i<10; i++) {
            final int finalI = i;
            myExecutors.execute(() -> System.out.println(Thread.currentThread().getName() +"==>" +finalI));
        }
        myExecutors.isRun=false;
    }
}
